<?php

declare(strict_types=1);

namespace app\controller\v1;

use app\model\TravelCoupon;
use app\model\TravelCouponUser;
use app\service\UserService;
use think\Request;

class CouponController extends BaseAPIController
{

    // 获取门票的优惠卷
    public function getTicketCoupons(Request $request)
    {
        try {
            $ticketId = $request->param('ticket_id');
            $orderAmount = (float) $request->param('order_amount', 0);
            $usageType = (int) $request->param('usage_type', 1);
            if ($orderAmount <= 0) {
                return $this->error('订单金额不能为空或小于等于0');
            }
            // 获取当前用户ID (需要根据实际的用户认证方式获取)
            $userId = UserService::getCurrentUserId();
            // 查询用户已领取且未使用的优惠券
            $availableCoupons = TravelCouponUser::alias('a1')
                ->leftJoin('travel_coupons a2', 'a1.coupon_id=a2.id')
                ->where('a1.user_id', $userId)
                ->where('a1.status', 1) // 1=未使用
                ->where('a2.status', 2) // 2=进行中
                ->where('a2.usage_type', "like", "%{$usageType}%")
                ->where('a2.start_time', '<=', date('Y-m-d H:i:s'))
                ->where('a2.end_time', '>=', date('Y-m-d H:i:s'))
                ->where('a2.min_spend', '<=', $orderAmount) // 满足使用门槛
                ->field('a1.id as recive_id,a2.*')
                ->select()
                ->toArray();
            if (empty($availableCoupons)) {
                return $this->success();
            }
            // $couponIds = array_column($userCoupons, 'coupon_id');
            // 查询符合条件的优惠券
            // $availableCoupons = TravelCoupon::whereIn('id', $couponIds)
            //     ->where('status', 2) // 2=进行中
            //     ->where('usage_type', "like", "%{$usageType}%")
            //     ->where('start_time', '<=', date('Y-m-d H:i:s'))
            //     ->where('end_time', '>=', date('Y-m-d H:i:s'))
            //     ->where('min_spend', '<=', $orderAmount) // 满足使用门槛
            //     ->select()
            //     ->toArray();
            // 格式化返回数据
            $result = [];

            foreach ($availableCoupons as $coupon) {
                // 找到对应的用户优惠券记录
                // $userCoupon = null;
                // foreach ($userCoupons as $uc) {
                //     if ($uc['coupon_id'] == $coupon['id']) {
                //         $userCoupon = $uc;
                //         break;
                //     }
                // }
                // if (!$userCoupon) continue;
                $discountAmount = 0;
                $discountText = '';
                // 计算优惠金额
                switch ($coupon['discount_type']) {
                    case 1: // 满减
                        $discountAmount = $coupon['discount_amount'];
                        $discountText = "满{$coupon['min_spend']}减{$coupon['discount_amount']}";
                        break;
                    case 2: // 直减
                        $discountAmount = $coupon['discount_amount'];
                        $discountText = "立减{$coupon['discount_amount']}元";
                        break;
                    case 3: // 折扣
                        $discountAmount = $orderAmount * (1 - $coupon['discount_rate'] / 10);
                        $discountText = "{$coupon['discount_rate']}折";
                        break;
                }

                // 确保优惠金额不超过订单金额
                $discountAmount = min($discountAmount, $orderAmount);

                $result[] = [
                    'id' => $coupon['id'],
                    'user_coupon_id' => $coupon['recive_id'],
                    // 'code' => $coupon['code'],
                    'name' => $coupon['name'],
                    'description' => $coupon['description'],
                    'discount_type' => $coupon['discount_type'],
                    'discount_amount' => $discountAmount,
                    'discount_text' => $discountText,
                    'min_spend' => $coupon['min_spend'],
                    'expire_date' => date('Y-m-d', strtotime($coupon['end_time'])),
                    // 'received_at' => $coupon['received_at']
                ];
            }

            // 按优惠金额降序排列
            usort($result, function ($a, $b) {
                return $b['discount_amount'] <=> $a['discount_amount'];
            });

            return $this->success($result);
        } catch (\Exception $e) {
            return $this->error('获取优惠券失败: ' . $e->getMessage());
        }
    }


    // 获取领券中心优惠券列表
    public function getCouponList()
    {
        try {
            // 获取当前用户ID
            $userId = UserService::getCurrentUserId();
            $couponModel = new TravelCoupon();
            // 查询进行中的优惠券
            $coupons = $couponModel->where('status', 2) // 2=进行中
                ->where('start_time', '<=', date('Y-m-d H:i:s'))
                ->where('end_time', '>=', date('Y-m-d H:i:s'))
                ->where('total_stock', '>', 'used_stock') // 还有库存
                ->order('created_at', 'desc')
                ->select()
                ->toArray();

            $result = [];

            foreach ($coupons as $coupon) {
                // 检查用户是否已领取此优惠券
                $userCouponCount = 0;
                if ($userId) {
                    $userCouponCount = TravelCouponUser::where('user_id', $userId)
                        ->where('coupon_id', $coupon['id'])
                        ->count();
                }

                // 判断是否已达到领取上限
                $received = $userCouponCount >= $coupon['per_limit'];
                // 计算优惠金额显示
                $amount = 0;
                $limit = '';
                // 随机颜色
                $types = ['primary', 'success', 'danger'];
                $type = $types[array_rand($types)]; //error,warning,success,primary
                $size = 'large';
                switch ($coupon['discount_type']) {
                    case 1: // 满减
                        $amount = (int)$coupon['discount_amount'];
                        $limit = $coupon['min_spend'] > 0 ? "满{$coupon['min_spend']}可用" : '无门槛';
                        // $type = $amount >= 100 ? 'error' : 'primary';
                        // $size = $amount >= 200 ? 'large' : 'normal';
                        break;
                    case 2: // 直减
                        $amount = (int)$coupon['discount_amount'];
                        $limit = '无门槛';
                        // $type = $amount >= 100 ? 'error' : 'primary';
                        // $size = $amount >= 200 ? 'large' : 'normal';
                        break;
                    case 3: // 折扣
                        $amount = $coupon['discount_rate'];
                        $limit = $coupon['min_spend'] > 0 ? "满{$coupon['min_spend']}可用" : '无门槛';
                        // $type = 'warning';
                        // $size = 'normal';
                        break;
                }

                // 根据优惠券类型设置描述
                $desc = $couponModel->couponType[(int)$coupon['coupon_type']];

                // 根据使用场景添加描述
                $usageTypes = empty($coupon['usage_type']) ? [] : json_decode($coupon['usage_type'], true);
                $usageDesc = [];
                foreach ($usageTypes as $typev) {
                    $usageDesc[] = $couponModel->usageType[(int)trim($typev)];
                }
                if (!empty($usageDesc)) {
                    $desc .= ' · ' . implode('/', $usageDesc);
                }
                if ($received) {
                    $type = 'info';
                }
                // if ($coupon['status'] == 2) {
                //     $type = 'success';
                // }
                // 'available': 'success',
                // 'used': 'info',
                // 'expired': 'error'
                $result[] = [
                    'id' => $coupon['id'],
                    'amount' => $amount,
                    'unit' => $coupon['discount_type'] == 3 ? '折' : '￥',
                    'title' => $coupon['name'],
                    'desc' => $desc,
                    'limit' => $limit,
                    'time' => '有效期至' . date('Y-m-d', strtotime($coupon['end_time'])),
                    'size' => $size,
                    'type' => $type,
                    'received' => $received,
                    'stock' => $coupon['total_stock'] - $coupon['used_stock'], // 剩余库存
                    'per_limit' => $coupon['per_limit'] // 每人限领数量
                ];
            }

            return $this->success($result);
        } catch (\Exception $e) {
            var_dump($e->getTraceAsString());
            return $this->error('获取优惠券列表失败: ' . $e->getMessage(), 400);
        }
    }


    // 领取优惠卷
    public function receiveCoupon()
    {
        try {
            $couponId = $this->request->get('coupon_id');
            $userId = UserService::getCurrentUserId();
            $couponModel = new TravelCoupon();
            $coupon = $couponModel->find($couponId);
            if (!$coupon) {
                return $this->error('优惠券不存在', 400);
            }
            if ($coupon['status'] != 2) {
                return $this->error('优惠券已过期或不可用', 400);
            }
            if ($coupon['total_stock'] <= $coupon['used_stock']) {
                return $this->error('优惠券已领完', 400);
            }
            $userCouponCount = TravelCouponUser::where('user_id', $userId)
                ->where('coupon_id', $couponId)
                ->count();
            if ($userCouponCount >= $coupon['per_limit']) {
                return $this->error('已领取过该优惠券', 400);
            }
            // 减库存
            $couponModel->where('id', $couponId)->setInc('used_stock');
            TravelCouponUser::insert([
                'coupon_id' => $couponId,
                'user_id' => $userId,
                'code' => generateVerifyCode(8),
                'received_at' => date('Y-m-d H:i:s'),
                'created_at' => time(),
                'updated_at' => time(),
            ]);
        } catch (\Exception $e) {
            return $this->error('领取优惠券失败: ' . $e->getMessage(), 400);
        }
        return $this->success();
    }


    //获取我的优惠卷列表
    public function getMyCouponList(Request $request)
    {
        try {
            $userId = UserService::getCurrentUserId();
            $page = (int) $request->param('page', 1);
            $limit = (int) $request->param('limit', 10);
            $status = $request->param('status', ''); // all, available, used, expired
            // 构建查询条件
            $query = TravelCouponUser::alias('tcu')
                ->leftJoin('travel_coupons tc', 'tcu.coupon_id = tc.id')
                ->where('tcu.user_id', $userId)
                ->field('tcu.*, tc.name, tc.description, tc.discount_type, tc.discount_amount, tc.discount_rate, tc.min_spend, tc.start_time, tc.end_time, tc.coupon_type, tc.usage_type');
            $couponModel = new TravelCoupon();
            // 根据状态筛选
            $currentTime = date('Y-m-d H:i:s');
            switch ($status) {
                case 'available':
                    $query->where('tcu.status', 1); // 未使用
                    //   ->where('tc.end_time', '>=', $currentTime); // 未过期
                    break;
                case 'used':
                    $query->where('tcu.status', 2); // 已使用
                    break;
                case 'expired':
                    $query->where('tc.end_time', '<', $currentTime);
                    // ->where('tcu.status', 1) // 未使用但已过期
                    break;
                default:
                    $query->where('tcu.status', 1);
            }

            // 分页查询
            $total = $query->count();
            $couponList = $query->order('tcu.created_at', 'desc')
                ->page($page, $limit)
                ->select()
                ->toArray();
            $result = [];

            foreach ($couponList as $item) {
                // 判断优惠券状态
                $couponStatus = 'available';
                if ($item['status'] == 2) {
                    $couponStatus = 'used';
                } elseif ($item['status'] == 1 && strtotime($item['end_time']) < time()) {
                    $couponStatus = 'expired';
                }
                // 计算优惠金额和单位
                $amount = 0;
                $unit = '￥';
                $couponLimit = '';

                switch ($item['discount_type']) {
                    case 1: // 满减
                        $amount = (int)$item['discount_amount'];
                        $couponLimit = $item['min_spend'] > 0 ? "满{$item['min_spend']}可用" : '无门槛';
                        break;
                    case 2: // 直减
                        $amount = (int)$item['discount_amount'];
                        $couponLimit = '无门槛';
                        break;
                    case 3: // 折扣
                        $amount = $item['discount_rate'];
                        $unit = '折';
                        $couponLimit = $item['min_spend'] > 0 ? "满{$item['min_spend']}可用" : '无门槛';
                        break;
                }

                // 根据优惠券类型和使用场景设置描述
                $desc = $couponModel->couponType[(int)$item['coupon_type']];

                // 根据使用场景添加描述
                if (!empty($item['usage_type'])) {
                    $usageTypes = empty($item['usage_type']) ? [] : json_decode($item['usage_type'], true);
                    $usageDesc = [];
                    foreach ($usageTypes as $typev) {
                        $usageDesc[] = $couponModel->usageType[(int)trim($typev)];
                    }
                    if (!empty($usageDesc)) {
                        $desc .= ' · ' . implode('/', $usageDesc);
                    }
                }

                // 如果有具体描述，优先使用
                if (!empty($item['description'])) {
                    $desc = $item['description'];
                }
                $couponData = [
                    'id' => $item['id'],
                    'coupon_id' => $item['coupon_id'],
                    'amount' => $amount,
                    'unit' => $unit,
                    'title' => $item['name'],
                    'desc' => $desc,
                    'limit' => $couponLimit,
                    'time' => '有效期至' . date('Y-m-d', strtotime($item['end_time'])),
                    'status' => $couponStatus,
                    'receiveTime' => date('Y-m-d H:i:s', $item['created_at'])
                ];
                // 如果已使用，添加使用时间
                if ($couponStatus === 'used' && !empty($item['updated_at'])) {
                    $couponData['useTime'] = $item['used_at'];
                }
                $result[] = $couponData;
            }
            return $this->success([
                'list' => $result,
                'total' => $total,
                'page' => $page,
                'limit' => $limit,
                'pages' => ceil($total / $limit)
            ]);
        } catch (\Exception $e) {
            trace('error', $e->getTraceAsString());
            return $this->error('获取我的优惠券列表失败: ' . $e->getMessage(), 400);
        }
    }
}
